/**
 * 事件相关的验证 Schema
 */

import { Type, Static } from '@sinclair/typebox'
import { UUIDSchema, PaginationQuerySchema } from './common.schema'

// ==================== 事件设置相关 ====================

/**
 * 重复规则配置
 */
export const RecurrenceConfigSchema = Type.Object({
    frequency: Type.Union([Type.Literal('DAILY'), Type.Literal('WEEKLY'), Type.Literal('MONTHLY')], {
        description: '重复频率'
    }),
    interval: Type.Optional(Type.Integer({ minimum: 1, description: '间隔（默认1）' })),
    count: Type.Optional(Type.Integer({ minimum: 1, description: '重复次数' })),
    until: Type.Optional(Type.String({ format: 'date-time', description: '重复结束日期' })),
    byWeekday: Type.Optional(
        Type.Array(Type.Integer({ minimum: 0, maximum: 6 }), {
            description: '按星期几重复（0=周日）'
        })
    ),
    byMonthDay: Type.Optional(
        Type.Array(Type.Integer({ minimum: 1, maximum: 31 }), {
            description: '按月中第几天重复'
        })
    )
})

/**
 * 时间阈值配置
 */
export const TimeThresholdsConfigSchema = Type.Object({
    gracePeriodMinutes: Type.Integer({ minimum: 0, description: '宽限期（分钟）' }),
    lateThresholdMinutes: Type.Integer({ minimum: 0, description: '迟到阈值（分钟）' }),
    absentThresholdMinutes: Type.Integer({ minimum: 0, description: '缺席阈值（分钟）' })
})

/**
 * 签到要求配置
 */
export const CheckInRequirementsConfigSchema = Type.Object({
    requireLocation: Type.Boolean({ description: '是否需要定位' }),
    requirePhoto: Type.Boolean({ description: '是否需要拍照' }),
    requireSecretCode: Type.Boolean({ description: '是否需要签到码' }),
    allowedRadius: Type.Optional(Type.Number({ minimum: 0, description: '允许签到半径（米）' }))
})

/**
 * 事件设置项
 */
export const EventSettingSchema = Type.Union([
    Type.Object({
        key: Type.Literal('RECURRENCE'),
        value: RecurrenceConfigSchema
    }),
    Type.Object({
        key: Type.Literal('TIME_THRESHOLDS'),
        value: TimeThresholdsConfigSchema
    }),
    Type.Object({
        key: Type.Literal('CHECKIN_REQUIREMENTS'),
        value: CheckInRequirementsConfigSchema
    })
])

// ==================== 创建事件 ====================

/**
 * 创建事件请求
 */
export const CreateEventSchema = Type.Object(
    {
        organizationId: UUIDSchema,
        title: Type.String({
            minLength: 1,
            maxLength: 100,
            description: '事件标题'
        }),
        description: Type.Optional(
            Type.String({
                maxLength: 500,
                description: '事件描述'
            })
        ),
        startAt: Type.String({
            format: 'date-time',
            description: '开始时间'
        }),
        endAt: Type.String({
            format: 'date-time',
            description: '结束时间'
        }),
        settings: Type.Optional(
            Type.Array(EventSettingSchema, {
                description: '事件设置'
            })
        ),
        eventCombinationId: Type.Optional(UUIDSchema)
    },
    {
        $id: 'CreateEvent',
        description: '创建事件请求'
    }
)

export type CreateEventRequest = Static<typeof CreateEventSchema>

/**
 * 创建事件响应
 */
export const EventDetailSchema = Type.Object(
    {
        id: UUIDSchema,
        title: Type.String(),
        description: Type.Optional(Type.String()),
        startAt: Type.String({ format: 'date-time' }),
        endAt: Type.String({ format: 'date-time' }),
        status: Type.Boolean({ description: '事件状态（启用/禁用）' }),
        settings: Type.Optional(Type.Array(EventSettingSchema))
    },
    {
        $id: 'EventDetail',
        description: '事件详情'
    }
)

export const CreateEventResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: EventDetailSchema
    },
    {
        $id: 'CreateEventResponse'
    }
)

// ==================== 更新事件 ====================

/**
 * 更新事件请求
 */
export const UpdateEventSchema = Type.Object(
    {
        title: Type.Optional(
            Type.String({
                minLength: 1,
                maxLength: 100,
                description: '事件标题'
            })
        ),
        description: Type.Optional(
            Type.String({
                maxLength: 500,
                description: '事件描述'
            })
        ),
        startAt: Type.Optional(
            Type.String({
                format: 'date-time',
                description: '开始时间'
            })
        ),
        endAt: Type.Optional(
            Type.String({
                format: 'date-time',
                description: '结束时间'
            })
        ),
        settings: Type.Optional(
            Type.Array(EventSettingSchema, {
                description: '事件设置'
            })
        )
    },
    {
        $id: 'UpdateEvent',
        description: '更新事件请求'
    }
)

export type UpdateEventRequest = Static<typeof UpdateEventSchema>

export const UpdateEventResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: EventDetailSchema
    },
    {
        $id: 'UpdateEventResponse'
    }
)

// ==================== 获取事件详情 ====================

export const GetEventResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: EventDetailSchema
    },
    {
        $id: 'GetEventResponse'
    }
)

// ==================== 删除事件 ====================

export const DeleteEventResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: Type.Object({
            deleted: Type.Boolean()
        })
    },
    {
        $id: 'DeleteEventResponse'
    }
)

// ==================== 事件列表查询 ====================

/**
 * 事件列表查询参数
 */
export const EventListQuerySchema = Type.Intersect(
    [
        PaginationQuerySchema,
        Type.Object({
            organizationId: Type.Optional(UUIDSchema),
            status: Type.Optional(Type.Boolean({ description: '筛选状态' })),
            startDate: Type.Optional(
                Type.String({
                    format: 'date-time',
                    description: '开始日期范围'
                })
            ),
            endDate: Type.Optional(
                Type.String({
                    format: 'date-time',
                    description: '结束日期范围'
                })
            ),
            keyword: Type.Optional(
                Type.String({
                    maxLength: 100,
                    description: '关键词搜索（标题/描述）'
                })
            )
        })
    ],
    {
        $id: 'EventListQuery',
        description: '事件列表查询参数'
    }
)

export type EventListQuery = Static<typeof EventListQuerySchema>

/**
 * 事件列表项（简化版）
 */
export const EventSummarySchema = Type.Object({
    id: UUIDSchema,
    title: Type.String(),
    description: Type.Optional(Type.String()),
    startAt: Type.String({ format: 'date-time' }),
    endAt: Type.String({ format: 'date-time' }),
    status: Type.Boolean(),
    organizationId: UUIDSchema,
    participantCount: Type.Optional(Type.Integer({ description: '参与人数' }))
})

export const EventListResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: Type.Object({
            data: Type.Array(EventSummarySchema),
            total: Type.Integer(),
            offset: Type.Integer(),
            limit: Type.Integer(),
            hasMore: Type.Boolean()
        })
    },
    {
        $id: 'EventListResponse'
    }
)

// ==================== 克隆事件 ====================

/**
 * 克隆事件请求
 */
export const CloneEventSchema = Type.Object(
    {
        newTitle: Type.Optional(
            Type.String({
                minLength: 1,
                maxLength: 100,
                description: '新事件标题（可选，默认添加"副本"）'
            })
        ),
        newStartAt: Type.String({
            format: 'date-time',
            description: '新的开始时间'
        }),
        newEndAt: Type.String({
            format: 'date-time',
            description: '新的结束时间'
        }),
        cloneSettings: Type.Optional(
            Type.Boolean({
                default: true,
                description: '是否克隆事件设置'
            })
        ),
        cloneParticipants: Type.Optional(
            Type.Boolean({
                default: true,
                description: '是否克隆参与者'
            })
        )
    },
    {
        $id: 'CloneEvent',
        description: '克隆事件请求'
    }
)

export type CloneEventRequest = Static<typeof CloneEventSchema>

export const CloneEventResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: EventDetailSchema
    },
    {
        $id: 'CloneEventResponse'
    }
)

// ==================== 初始化事件实例 ====================

/**
 * 初始化事件实例请求
 */
export const InitializeEventInstancesSchema = Type.Object(
    {
        eventId: UUIDSchema,
        force: Type.Optional(
            Type.Boolean({
                default: false,
                description: '是否强制重新生成（删除已有实例）'
            })
        )
    },
    {
        $id: 'InitializeEventInstances',
        description: '初始化事件实例请求'
    }
)

export type InitializeEventInstancesRequest = Static<typeof InitializeEventInstancesSchema>

export const InitializeEventInstancesResponseSchema = Type.Object(
    {
        success: Type.Literal(true),
        data: Type.Object({
            eventId: UUIDSchema,
            instanceCount: Type.Integer({ description: '生成的实例数量' }),
            firstInstanceDate: Type.Optional(Type.String({ format: 'date-time' })),
            lastInstanceDate: Type.Optional(Type.String({ format: 'date-time' }))
        })
    },
    {
        $id: 'InitializeEventInstancesResponse'
    }
)
